package com.rill.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import sun.rmi.transport.proxy.HttpReceiveSocket;

import com.opensymphony.xwork2.ActionSupport;
import com.rill.po.User;
import com.rill.service.UserService;

/**
 * Action：业务逻辑控制器：1.封装参数 2.返回逻辑视图 1.需要对应前端传来的参数设置属性和方法(用于http请求和响应)
 * 2.设置逻辑视图-->物理视图
 */
public class RegisterAction extends ActionSupport {
	private static final long serialVersionUID = 1L;

	/** 引入service，action进行业务操作 */
	private UserService userService;

	/** 属性封装前端参数 */
	private String username;// 用户名
	private String password;// 密码
	private String repassword;// 重复密码
	private String nickname;// 昵称
	private String question;// 密保问题
	private String answer;// 答案

	/**
	 * 对应的方法，用于前端传递数据、响应数据
	 */
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRepassword() {
		return repassword;
	}

	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getQuestion() {
		return question;
	}

	public void setQuestion(String question) {
		this.question = question;
	}

	public String getAnswer() {
		return answer;
	}

	public void setAnswer(String answer) {
		this.answer = answer;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/*
	 * 返回的逻辑视图，对应struts.xml文件进行配置
	 */
	@Override
	public String execute() throws Exception {
		// 封装一个user对象(把前端传的参数封装给po)从注册表单得来的
		User user = new User();//po对象
		user.setUsername(username);//前端传的值封装到po中
		user.setPassword(password);
		user.setNickname(nickname);
		user.setQuestion(question);
		user.setAnswer(answer);
		
		
		//先获取request
		HttpServletRequest request=ServletActionContext.getRequest();
		if (userService.registerUser(user)) {//调用serviceimpl查数据库中没有此user
			request.setAttribute("url", "login.jsp");
			request.setAttribute("info", "成功");
			return SUCCESS;
		} else {//已经有此用户
			request.setAttribute("url", "register.jsp");
			request.setAttribute("info", "失败");
			return ERROR;
		}
	}

	/*
	 * 检验方法：字段校验和非字段校验；使用校验文件不需要此方法
	 * 
	 * @Override public void validate() { if(username == null ||
	 * "".equals(username.trim())){ //非字段校验 this.addActionError("用户名不能为空");
	 * 
	 * //字段校验 this.addFieldError(username, "用户名不能为空"); } }
	 */

}
